package com.hubujun.driverlicense.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;


import com.hubujun.driverlicense.ApplicationContext;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

public class Util {

    public static final String UNKNOWN = "UNKNOWN";

    public static final String NOPERMISSION = "NOPERMISSION";

    public static final String EXCEPTION = "EXCEPTION";

    public static final String DEFAULT_ZERO = "000000000000000";

    public static boolean isEmpty(String s) {
        return s == null || s.length() <= 0;
    }

    public static String getString(String s) {
        if (s == null)
            s = "";
        return s;
    }

    public static boolean isEmpty(byte[] data) {
        return data == null || data.length <= 0;
    }

    public static int intValue(Integer integer) {
        return integer == null ? 0 : integer.intValue();
    }

    public static long parseLong(String digit) {
        long value = -1L;
        if (digit != null) {
            try {
                value = Long.parseLong(digit);
            } catch (Exception e) {
            }
        }
        return value;
    }

    public static long curTimeFromBoot() {
        return SystemClock.elapsedRealtime();
    }

    public static long intervalByBoot(long time) {
        return SystemClock.elapsedRealtime() - time;
    }

    public static long curTime() {
        return System.currentTimeMillis();
    }

    public static long curTimeInSecond() {
        return System.currentTimeMillis() / 1000L;
    }

    public static long intervalBySysInSecond(long time) {
        return System.currentTimeMillis() / 1000L - time;
    }

	public static int tcpSendPacketRawLen(int len) {
		return len + (40 + 52 * (1 + (len - 1) / 1462));
	}

	public static int tcpReceivePacketRawLen(int len) {
		return len + (40 + 52 * (1 + (len - 1) / 1462));
	}

	public static int httpSendPacketRawLen(int len) {
		return len + (224 + 52 * (1 + (len - 1) / 1462));
	}

	public static int httpReceivePacketRawLen(int len) {
		return len + (208 + 52 * (1 + (len - 1) / 1462));
	}

	private static final BroadcastReceiver sdcardListener = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {

			} else if (Intent.ACTION_MEDIA_UNMOUNTED.equals(action) || Intent.ACTION_MEDIA_BAD_REMOVAL.equals(action)) {

			}
		}
	};

	public static boolean canWriteExternal() {
		try {
			if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
				return false;
			File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
			return f.exists() && f.canWrite();
		} catch (Exception e) {
			Ln.e(e);
		}
		return false;
	}

	public static void registerStorage() {
		IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
		intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
		intentFilter.addDataScheme("file");
		ApplicationContext.getContext().registerReceiver(sdcardListener, intentFilter);
	}

	/**
	 * 检查 这样文件大小能否保存到SD卡
	 * 
	 * @param filesize
	 * @return
	 */
	public static boolean checkCanSaveSdcard(long filesize) {
		boolean ret = false;
		if (canWriteExternal()) {
			StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
			long blockSize = stat.getBlockSize();
			long availableBlocks = stat.getAvailableBlocks();
			if (filesize < availableBlocks * blockSize) {
				ret = true;
			}
		}
		return ret;
	}

	public static boolean isProcessRunning(Context context, String name) {
		if (name.startsWith(":"))
			name = context.getPackageName() + name;
		Iterator<RunningAppProcessInfo> iterator = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getRunningAppProcesses().iterator();
		while (iterator.hasNext()) {
			RunningAppProcessInfo runningappprocessinfo = iterator.next();
			if (runningappprocessinfo != null && runningappprocessinfo.processName != null && runningappprocessinfo.processName.equals(name)) {
				Ln.d("process %s is running", name);
				return true;
			}
		}
		Ln.d("process %s is not running", name);
		return false;
	}

    public static String getMac(Context context) {
        String mac = UNKNOWN;
        if (Util.checkPermission(context, "android.permission.ACCESS_WIFI_STATE")) {
            try {
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                if (wifiManager != null) {
                    WifiInfo wifiinfo = wifiManager.getConnectionInfo();
                    if (wifiinfo != null)
                        mac = wifiinfo.getMacAddress();
                }
            } catch (Exception e) {
            }
        } else
            mac = NOPERMISSION;

		if (mac != null && !mac.equals(NOPERMISSION)) {
			if (mac.length() > 0)
				return mac;
		}

		StringBuilder sb;
		BufferedReader bufferedreader;
		try {
			sb = new StringBuilder(100);
			bufferedreader = new BufferedReader(new FileReader("/sys/class/net/eth0/address"));
			char ac[] = new char[1024];
			int len;
			while ((len = bufferedreader.read(ac)) > 0) {
				sb.append(String.valueOf(ac, 0, len));
			}
			bufferedreader.close();
			mac = sb.substring(0, 17).toUpperCase().toString();
		} catch (Exception exception1) {
			mac = EXCEPTION;
			Ln.e(exception1);
		}
		if (mac == null) {
			mac = UNKNOWN;
		}
		return mac;
	}

    public static String getAndroidId(Context context) {
        String id = UNKNOWN;
        try {
            String v = Settings.Secure.getString(context.getContentResolver(), "android_id");
            if (!isEmpty(v)) {
                id = v;
            }
        } catch (Exception e) {
            id = EXCEPTION;
        }
        if (id == null) {
            id = UNKNOWN;
        }
        return id;
    }

    public static String[] getVersion() {
        String strOSInfo = "";
        try {
            Process process = Runtime.getRuntime().exec("cat /proc/version");
            InputStream outs = process.getInputStream();
            InputStreamReader isrout = new InputStreamReader(outs);
            BufferedReader brout = new BufferedReader(isrout, 8 * 1024);

            String line;
            while ((line = brout.readLine()) != null) {
                strOSInfo += line;
            }
        } catch (IOException e) {
        }
        String[] values = new String[4];
        if (strOSInfo.length() > 0) {
            String[] strOSInfos = strOSInfo.split(" ");
            if (strOSInfos != null && strOSInfos.length >= 3) {
                values[0] = strOSInfos[0];
                values[1] = strOSInfos[2];
            }
        }
        values[2] = Build.VERSION.SDK;
        values[3] = Build.VERSION.RELEASE;
        return values;
    }

    public static String[] getMemory() {
        String strItem = "";
        String[] values = new String[3];
        try {
            FileReader fr = new FileReader("/proc/meminfo");
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
            while ((strItem = localBufferedReader.readLine()) != null) {
                if (strItem.contains("MemTotal:")) {
                    values[0] = strItem.substring(9).trim();
                } else if (strItem.contains("MemFree:")) {
                    values[1] = strItem.substring(8).trim();
                } else if (strItem.contains("Inactive:")) {
                    values[2] = strItem.substring(9).trim();
                }
            }
            localBufferedReader.close();
        } catch (IOException e) {
        }
        return values;
    }

    public static String getMaxCpuFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }
        return result.trim() + " KHZ";
    }

    public static String getMinCpuFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }
        return result.trim() + " KHZ";
    }

	/**
	 * 实时获取CPU当前频率（单位KHZ）
	 */
	public static String getCurCpuFreq() {
		String result = "N/A";
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
			br = new BufferedReader(fr);
			String text = br.readLine();
			result = text.trim();
		} catch (FileNotFoundException e) {
			Ln.e(e, "getCurCpuFreq----exception--");

		} catch (IOException e) {
			Ln.e(e, "getCurCpuFreq----exception--");
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (fr != null) {
				try {
					fr.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result + " KHZ";
	}

    public static String getCpu() {
        FileReader filereader = null;
        BufferedReader bufferedreader = null;
        String cpu = UNKNOWN;
        try {
            filereader = new FileReader("/proc/cpuinfo");
            bufferedreader = new BufferedReader(filereader);
            cpu = bufferedreader.readLine().split(":\\s+", 2)[1];
        } catch (Exception exception4) {
            cpu = EXCEPTION;
        } finally {
            try {
                if (bufferedreader != null)
                    bufferedreader.close();
                if (filereader != null)
                    filereader.close();
            } catch (Exception e) {
            }
        }
        return cpu;

    }

	public static String getSensor(Context context) {
		Ln.d("getSensor start");
		StringBuilder sb = new StringBuilder();
		if (Integer.parseInt(Build.VERSION.SDK) < 10) {
			Ln.d("getSensor End");
			return sb.toString();
		} else {
			int num = 0;
			Class<?> cameraClass = null;
			try {
				cameraClass = Class.forName("android.hardware.Camera");
				num = ((Integer) cameraClass.getMethod("getNumberOfCameras", new Class[0]).invoke(cameraClass, new Object[0])).intValue();
			} catch (Exception e) {
			}

			String facingFront;
			String faceingBack;
			if (num != 0) {
				facingFront = "X";
				faceingBack = "X";
				Class<?> cameraInfoClass = null;
				Method method = null;
				Object obj = null;
				try {
					cameraInfoClass = Class.forName("android.hardware.Camera$CameraInfo");
					obj = cameraInfoClass.newInstance();
					Method[] amethod = cameraClass.getMethods();
					for (int i = 0; i < amethod.length; i++) {
						Method method1 = amethod[i];
						if (method1.getName().equals("getCameraInfo")) {
							method = method1;
							break;
						}
					}
				} catch (Exception e) {
				}
				Field field = null;
				Field field1 = null;
				Field field2 = null;
				try {
					field = cameraInfoClass.getField("facing");
					field1 = cameraInfoClass.getField("CAMERA_FACING_BACK");
					field2 = cameraInfoClass.getField("CAMERA_FACING_FRONT");
				} catch (Exception e) {
				}

				if (method != null) {
					for (int i = 0; i < num; i++) {
						Object params[] = new Object[2];
						params[0] = Integer.valueOf(i);
						params[1] = obj;
						try {
							method.invoke(cameraClass, params);
							int facing = field.getInt(obj);
							int facing_back = field1.getInt(obj);
							int facing_front = field2.getInt(obj);
							if (facing != facing_back) {
								if (facing == facing_front) {
									facingFront = "Y";
									if (num == 1)
										faceingBack = "N";
								}
							} else {
								faceingBack = "Y";
								if (num == 1)
									facingFront = "N";

							}
						} catch (Exception e) {
						}
					}
				}
			} else {
				facingFront = "N";
				faceingBack = "N";
			}
			SensorManager sensormanager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
			String accelerometer;
			if (sensormanager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) == null) {
				accelerometer = "N";
			} else {
				accelerometer = "Y";
			}
			String gyroscope;
			if (sensormanager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) == null) {
				gyroscope = "N";
			} else {
				gyroscope = "Y";
			}
			sb.append(facingFront).append(faceingBack).append(accelerometer).append(gyroscope);
			Ln.d("getSensor End");
			return sb.toString();
		}
	}

	public static long getRamSize() {
		long size = 0;
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader("/proc/meminfo");
			br = new BufferedReader(fr, 8192);
			String[] info = br.readLine().split(":\\s+", 2);
			if (info.length > 0) {
				size = Long.parseLong(info[1].toLowerCase().replace("kb", "").trim()) / 1024;
			}
			br.close();
			fr.close();
		} catch (IOException ioexception2) {
			Ln.e(ioexception2);
			size = -2;
		} finally {
			try {
				if (br != null)
					br.close();
				if (fr != null)
					fr.close();
			} catch (IOException e) {
			}
		}
		return size;

	}

	public static long getRomSize() {
		long size = 0;
		try {
			StatFs statfs = new StatFs(Environment.getDataDirectory().getPath());
			long i = statfs.getBlockSize();
			long j = statfs.getBlockCount();
			size = (j * i) / 1024 / 1024;
		} catch (Exception e) {
			size = -2;
			Ln.e(e);
		}
		return size;
	}

    public static boolean checkPermission(Context context, String permission) {
        if (context != null) {
            try {
                PackageManager localPackageManager = context.getPackageManager();
                return localPackageManager.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED;
            } catch (Exception e) {
            }
        }
        return false;
    }

    public static String getImei(Context context) {
        String imei = UNKNOWN;
        try {
            if (checkPermission(context, "android.permission.READ_PHONE_STATE")) {
                TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                if (telephonyManager != null)
                    imei = telephonyManager.getDeviceId();
            } else {
                imei = "NOPERMISSION";
            }
        } catch (Exception exception) {
            imei = EXCEPTION;
        }
        if (imei == null) {
            imei = UNKNOWN;
        }
        return imei;
    }

    public static String getImsi(Context context) {
        String imsi = UNKNOWN;
        try {
            if (checkPermission(context, "android.permission.READ_PHONE_STATE")) {
                TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                if (telephonyManager != null)
                    imsi = telephonyManager.getSubscriberId();
                if (imsi == null) {
                    return "UNKNOWN";
                }
            } else {
                imsi = "NOPERMISSION";
            }
        } catch (Exception exception) {
            imsi = EXCEPTION;
        }
        return imsi;
    }

    public static String getDeviceId(Context context) {
        String deviceId = "";
        try {
            deviceId = Settings.System.getString(context.getContentResolver(), "dl_device_id");
            Ln.d("getDeviceId  getContentResolver deviceId=%s", deviceId);

            if (TextUtils.isEmpty(deviceId) || Util.DEFAULT_ZERO.equalsIgnoreCase(deviceId) || Util.UNKNOWN.equalsIgnoreCase(deviceId) || "UNKOWN".equalsIgnoreCase(deviceId)) {
                deviceId = Util.getReplaceDeviceId(context);
                Settings.System.putString(context.getContentResolver(), "dl_device_id", deviceId);
            }
        } catch (Exception e) {
            Ln.e(e);
            if (TextUtils.isEmpty(deviceId)) {
                deviceId = Util.getReplaceDeviceId(context);
                try {
                    Settings.System.putString(context.getContentResolver(), "dl_device_id", deviceId);
                } catch (Exception e1) {
                    Ln.e(e1);
                }
            }
        }
        Ln.d("getDeviceId  deviceId=%s", deviceId);

        return deviceId;
    }

    public static String getReplaceDeviceId(Context context) {
        String deviceId = Util.getImei(context);
        Ln.d("getReplaceDeviceId type = imei deviceId=%s", deviceId);
        if (TextUtils.isEmpty(deviceId) || deviceId.equalsIgnoreCase(Util.UNKNOWN) || deviceId.equalsIgnoreCase(Util.EXCEPTION) || deviceId.equalsIgnoreCase(Util.NOPERMISSION) || deviceId.equalsIgnoreCase(Util.DEFAULT_ZERO)) {
            deviceId = Util.getImsi(context);
            Ln.d("getReplaceDeviceId type = imsi deviceId=%s", deviceId);
            if (TextUtils.isEmpty(deviceId) || deviceId.equalsIgnoreCase(Util.UNKNOWN) || deviceId.equalsIgnoreCase(Util.EXCEPTION) || deviceId.equalsIgnoreCase(Util.NOPERMISSION) || deviceId.equalsIgnoreCase(Util.DEFAULT_ZERO)) {
                deviceId = Util.getMac(context);
                Ln.d("getReplaceDeviceId type = mac deviceId=%s", deviceId);
                if (TextUtils.isEmpty(deviceId) || deviceId.equalsIgnoreCase(Util.UNKNOWN) || deviceId.equalsIgnoreCase(Util.EXCEPTION) || deviceId.equalsIgnoreCase(Util.NOPERMISSION) || deviceId.equalsIgnoreCase(Util.DEFAULT_ZERO)) {
                    deviceId = Util.getAndroidId(context);
                    Ln.d("getReplaceDeviceId type = androidId deviceId=%s", deviceId);
                    if (TextUtils.isEmpty(deviceId) || deviceId.equalsIgnoreCase(Util.UNKNOWN) || deviceId.equalsIgnoreCase(Util.EXCEPTION) || deviceId.equalsIgnoreCase(Util.NOPERMISSION) || deviceId.equalsIgnoreCase(Util.DEFAULT_ZERO)) {
                        deviceId = "UUID" + UUID.randomUUID().toString();
                        Ln.d("getReplaceDeviceId type = uuid deviceId=%s", deviceId);
                    }
                } else {
                    deviceId = deviceId.replaceAll(":", "");
                }
            }
        }
        return deviceId;
    }

    public static String getModel() {
        String ret = UNKNOWN;
        try {
            ret = Build.MODEL;
        } catch (Exception e) {
            ret = EXCEPTION;
        }
        return ret;
    }

    public static String getRelease() {
        String ret = UNKNOWN;
        try {
            ret = Build.VERSION.RELEASE;
        } catch (Exception e) {
            ret = EXCEPTION;
        }
        return ret;
    }

    public static String getCountry() {
        String s3 = UNKNOWN;
        try {
            s3 = Locale.getDefault().getCountry();
        } catch (Exception e) {
            s3 = EXCEPTION;
        }
        return s3;
    }

    public static String getLanguage() {
        String s1 = UNKNOWN;
        try {
            s1 = Locale.getDefault().getLanguage();
        } catch (Exception e) {
            s1 = EXCEPTION;
        }
        return s1;

    }

    public static String getSimOperator(Context context) {
        String s1 = UNKNOWN;
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            try {
                s1 = telephonyManager.getSimOperator();
            } catch (Exception e) {
                s1 = EXCEPTION;
            }
        }
        return s1;
    }

    public static String getNetWorkType(Context context) {
        String s1 = UNKNOWN;
        if (!checkPermission(context, "android.permission.ACCESS_NETWORK_STATE")) {
            s1 = "NOPERMISSION";
        } else {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            NetworkInfo networkinfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (networkinfo != null) {
                if (networkinfo.getType() != ConnectivityManager.TYPE_WIFI) {
                    if (networkinfo.getType() != ConnectivityManager.TYPE_MOBILE || telephonyManager == null) {
                        return s1;
                    } else {
                        int type = telephonyManager.getNetworkType();
                        if (type == TelephonyManager.NETWORK_TYPE_CDMA) {
                            s1 = "CDMA";
                        }
                        if (type == TelephonyManager.NETWORK_TYPE_EDGE) {
                            s1 = "EDGE";
                        }
                        if (type == TelephonyManager.NETWORK_TYPE_EVDO_0) {
                            s1 = "EVDO_0";
                        }
                        if (type == TelephonyManager.NETWORK_TYPE_EVDO_A) {
                            s1 = "EVDO_A";
                        }
                        if (type == TelephonyManager.NETWORK_TYPE_GPRS) {
                            s1 = "GPRS";
                        }
                        if (type == TelephonyManager.NETWORK_TYPE_HSDPA) {
                            s1 = "HSDPA";
                        }
                        if (type == TelephonyManager.NETWORK_TYPE_HSPA) {
                            s1 = "HSPA";
                        }
                        if (type == TelephonyManager.NETWORK_TYPE_HSUPA) {
                            s1 = "HSUPA";
                        }
                        if (type == TelephonyManager.NETWORK_TYPE_UMTS) {
                            s1 = "UMTS";
                        }
                        if (type == TelephonyManager.NETWORK_TYPE_UNKNOWN) {
                            s1 = "UNKNOWN";
                        }
                        if (type == TelephonyManager.NETWORK_TYPE_1xRTT) {
                            s1 = "1xRTT";
                        }
                        if (type == 11) {
                            s1 = "iDen";
                        }
                        if (type == 12) {
                            s1 = "EVDO_B";
                        }
                        if (type == 13) {
                            s1 = "LTE";
                        }
                        if (type == 14) {
                            s1 = "eHRPD";
                        }
                        if (type == 15) {
                            s1 = "HSPA+";
                        }
                    }
                } else {
                    s1 = "wifi";

                }
            }
        }
        return s1;

    }

    public static String getLocalIpAddress() {
        Enumeration<NetworkInterface> enumeration;
        try {
            enumeration = NetworkInterface.getNetworkInterfaces();
            while (enumeration.hasMoreElements()) {
                Enumeration<InetAddress> enu = enumeration.nextElement().getInetAddresses();
                while (enu.hasMoreElements()) {
                    InetAddress inetaddress = enu.nextElement();
                    if (!inetaddress.isLoopbackAddress()) {
                        return inetaddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException e) {
        }
        return null;
    }

    public static String getBrand() {
        String s1 = UNKNOWN;
        try {
            s1 = Build.BRAND;
        } catch (Exception e) {
            s1 = EXCEPTION;
        }
        return s1;
    }

    public static String getAppVersionName(Context context) {
        PackageManager packagemanager = context.getPackageManager();
        String name = UNKNOWN;
        try {
            name = packagemanager.getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (Exception exception) {
            name = EXCEPTION;
        }
        return name;
    }

    /**
     * To determine whether it contains a gyroscope
     *
     * @return
     */
    public static boolean isHaveGravity(Context context) {
        SensorManager manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        if (manager == null) {
            return false;
        }
        return true;
    }

    public static boolean isHaveGPS(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return locationManager == null ? false : true;
    }

    public static int getAppVersion(Context context) {
        int s2 = -1;
        try {
            PackageManager packagemanager = context.getPackageManager();
            PackageInfo packageinfo = packagemanager.getPackageInfo(context.getPackageName(), 0);
            s2 = packageinfo.versionCode;
        } catch (Exception e) {
            s2 = -2;
        }
        return s2;
    }


    public static String getResolution(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        float rate = 0.5f * dm.widthPixels / dm.densityDpi;
        return dm.widthPixels + "x" + dm.heightPixels + "- densityDpi: " + dm.densityDpi + "- rate: " + rate;
    }

    public static int getPhoneType(Context context) {
        int s1 = -1;
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            try {
                s1 = telephonyManager.getPhoneType();
            } catch (Exception e) {
                s1 = -2;
            }
        }
        return s1;

    }

    /**
     * Get device name, manufacturer + model
     *
     * @return device name
     */
    public static String getDeviceName() {
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;

        if (model.startsWith(manufacturer)) {
            return capitalize(model);
        } else {
            return capitalize(manufacturer) + " " + model;
        }
    }

    /**
     * Capitalize the first letter
     *
     * @param s model,manufacturer
     * @return Capitalize the first letter
     */
    private static String capitalize(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        char first = s.charAt(0);
        if (Character.isUpperCase(first)) {
            return s;
        } else {
            return Character.toUpperCase(first) + s.substring(1);
        }
    }

    public static boolean isHaveBT() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        return adapter != null;
    }

    /**
     * Judge wifi is available
     *
     * @return
     */
    public static boolean isWiFiActive(Context context) {
        if (checkPermission(context, "android.permission.ACCESS_NETWORK_STATE")) {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo[] info = connectivity.getAllNetworkInfo();
                if (info != null) {
                    for (int i = 0; i < info.length; i++) {
                        if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) {
                            return true;
                        }
                    }
                }
            }
            return false;
        } else {
            return false;
        }
    }

    /**
     * get APPKEY
     *
     * @return appkey
     */
    public static String getAppKey(Context paramContext) {
        if (paramContext == null)
            return "";
        try {
            ApplicationInfo info = paramContext.getPackageManager().getApplicationInfo(paramContext.getPackageName(), 128);
            if (info != null) {
                String key = info.metaData.getString("UMS_APPKEY");
                if (key != null) {
                    return key;
                }
            }
        } catch (Exception ex) {
        }
        return "";
    }

    /**
     * get currnet activity's name
     *
     * @param context
     * @return
     */
    public static String getActivityName(Context context) {
        if (context == null)
            return "";

        if (context instanceof Activity) {
            return ((Activity) context).getLocalClassName();
        } else {
            ComponentName cn = getComponent(context);
            if (cn != null)
                return cn.getShortClassName();
            else {
                Ln.e("lost permission android.permission.GET_TASKS");
                return "";
            }
        }
    }

    public static ComponentName getComponent(Context context) {
        if (checkPermission(context, "android.permission.GET_TASKS")) {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> runningTaskInfos = am.getRunningTasks(1);
            if (runningTaskInfos.size() > 0) {
                return runningTaskInfos.get(0).topActivity;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * Determine the current network type
     *
     * @param context
     * @return
     */
    public static boolean isNetworkTypeWifi(Context context) {
        if (checkPermission(context, "android.permission.INTERNET")) {
            ConnectivityManager cManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = cManager.getActiveNetworkInfo();

            if (info != null && info.isAvailable() && info.getTypeName().equals("WIFI")) {
                return true;
            }
        }
        return false;
    }

    /**
     * Testing equipment networking and networking WIFI
     *
     * @param context
     * @return true or false
     */
    public static boolean isNetworkAvailable(Context context) {
        if (checkPermission(context, "android.permission.INTERNET")) {
            ConnectivityManager cManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = cManager.getActiveNetworkInfo();
            if (info != null && info.isAvailable() && info.isConnected()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    /**
     * Get the current time format yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getTime() {
        return Util.getTime(System.currentTimeMillis());
    }

    public static String getTime(long time) {
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    public static boolean isBackground(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess == null)
                continue;
            if (appProcess.pid == pid) {
                Ln.e("appProcess.importance is %d", appProcess.importance);
                if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }


}
